<template>
  <div class="dynamicTab" :style="commpStyle">
    <el-tabs :tab-position="tabAttr.tabPosition" v-model="dynamicTabsValue" type="card" :style="tabStyle"
             @tab-click="tabClick" :before-leave="beforeLeave" @tab-remove="removeTab">
      <el-tab-pane class="dynamicTabPane" :lazy="enableLazy" :closable="enabledClose"
                   v-for="(item, index) in dynamicTabs"
                   :key="item.name+'_'+index"
                   :label="item.title"
                   :name="item.name"
      >
            <span v-if="item.icon" class="custom-tree-node" slot="label">
                <svg class="iconfont" aria-hidden="true">
                    <use :xlink:href=getIconFont(item)></use>
                </svg>
             {{ item.title }}
            </span>
        <div v-else class="tabLabel" slot="label"> {{ item.title }}</div>
        <!-- <div v-if="item.tabConfig && item.tabConfig.showMode == 'comps' && item.name == nowPage">
            <layoutContainer  :layout="item.tabConfig.paramRender"></layoutContainer>
        </div> -->
        <commonConfigForm
          v-if="item.tabConfig && item.tabConfig.showMode == 'designScheme' && item.name == dynamicTabsValue"
          ref="commonConfigForm"
          :option="item.tabConfig ? item.tabConfig.paramRendert:{}"
          :default-data="item.tabConfig ? item.tabConfig.rendert:{}"
        >
        </commonConfigForm>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import baseComp from "./baseComp";
import layoutContainer from "./layoutContainer";


export default {
  name: "commonTab",
  extends: baseComp,
  components: {
    layoutContainer,
  },
  props: ["enabledClose", "enabledHide", "enableLazy", "tabAttr", "tabLayout", "tabPanelHeader"],
  watch: {
    tabAttr: {
      handler(newVal) {
        this.tabStyles.height = newVal.tabHide;
        this.tabStyles.width = newVal.tabWide;
        //根据配置属性动态设置样式
        switch (newVal.tabPosition) {
          case "top":
            let dynamicTab = document.getElementsByName("dynamicTab el-tab-pane");
            console.log(dynamicTab);
            break;
          case "right":

            break;
          case "bottom":
            break;
          case "left":
            break;
          default:
            break;
        }
      },
      immediate: true, //刷新加载 立马触发一次handler
      deep: true, // 可以深度检测到 obj 对象的属性值的变化
    },
    tabPanelHeader: {
      handler(v) {
        if (v) {
          for (let i = 0; i < v.length; i++) {
            this.receiveData(v[i])
            if(v[i].activity){
              this.tabClick(v[i])
            }
          }
        }
      },
      immediate: true,
      deep: true,
    }

  },
  data() {
    return {
      dynamicTabsValue: null,
      dynamicTabs: [],
      tabIndex: 2,
      tabStyles: {
        height: "100%",
        width: "100%"
      },
      cacheTab: {},
    }
  },
  created() {
    this.loadTheme(this.$options.name)
  },
  mounted() {
    // let tabNode = {
    //             title: 'Floorplan',
    //             name: '测试工程.Floorplan',
    //             icon: "el-icon-celvezhihangpeizhi",
    //             tabType: 'D',
    //         }
    //  this.addTab(tabNode);
    // this.tabStyles.height = this.tabAttr.tabHide;
    // this.tabStyles.width = this.tabAttr.tabWide;
    //  let attrNode = {
    //             title: '属性',
    //             name: '测试工程.属性',
    //             icon: "",
    //             tabType: 'attr',
    //         }
    //  this.receiveData(attrNode);
    //  let attrNode2 = {
    //             title: '属性2',
    //             name: '测试工程.属性2',
    //             icon: "",
    //             tabType: 'attr',
    //         }
    //  this.receiveData(attrNode2);
  },
  methods: {
    getIconFont(data) {
      let icon = "#" + data.icon;
      return icon;
    },
    //修改排列顺序
    updateDynamicTabList() {
      // 修改顺序
      let parse = JSON.parse(JSON.stringify(this.dynamicTabs));
      let newParse = []
      if (this.tabPanelHeader && this.tabPanelHeader.length > 0) {
        for (let i = 0; i < this.tabPanelHeader.length; i++) {
          let headerElement = this.tabPanelHeader[i];
          for (let j = 0; j < parse.length; j++) {
            let parseElement = parse[j];
            if (headerElement.tabType == parseElement.tabType) {
              newParse[i] = parseElement;
              break;
            }
          }
        }
      }
      console.log(newParse)
    },
    receiveData(tabNode) {
      let that = this;
      //首先检查当前tab是否存在
      let flag = false;
      for (let i = 0; i < that.dynamicTabs.length; i++) {
        let ss = that.dynamicTabs[i];
        if (ss && ss.name == tabNode.name) {
          flag = true;
          if (tabNode.activity) {
            that.dynamicTabsValue = tabNode.name;
          }
          break;
        }
      }
      if (flag) {
        console.log("当前表格已经存在了");
        return;
      }

      that.addTab(tabNode, that)
    },
    /**
     * 动态tab新增接口
     * {
     *      title: 'Floorplan',
                name: '测试工程.Floorplan',
                icon: "el-icon-celvezhihangpeizhi",
                content: 'Tab 1 content',
                activity: true
     * }
     * @param {*} tabNode 传入参数
     */
    async addTab(tabNode, that) {
      //layoutName
      if (that.tabLayout && that.tabLayout.length > 0) {
        for (let i = 0; i < that.tabLayout.length; i++) {
          let tabNodeTemp = JSON.parse(JSON.stringify(that.tabLayout[i]));
          if (tabNodeTemp.tabType == tabNode.tabType) {
            //判断是否为配置界面，是则获取配置界面数据
            // 判断当前是否是选中页
            if (tabNodeTemp.showMode == "designScheme") {
              let paramRender = {};
              await that.$myAxios.request('post', '/uavMesh/operation/getOperationUiContentByProcessKey', {processKey: tabNodeTemp.showUrl})
                .then((res) => {
                  if (res.data.code == 200) {
                    let data = res.data.data;
                    if (data.design) {
                      paramRender = data.design.uiContent;
                    }
                  } else {
                    this.$message.error('获取设计方案界面失败！')
                  }
                });
              paramRender.pageName = tabNodeTemp.showUrl;
              paramRender.theme = this.theme;
              tabNodeTemp['paramRendert'] = paramRender;
            }
            tabNodeTemp.rendert = tabNode.viewData;
            tabNode["tabConfig"] = tabNodeTemp;
            if (tabNode.activity) {
              that.dynamicTabsValue = tabNode.name;
              that.$nextTick(() => {
                that.initNav(tabNode, that);
              })
            }

            // 判断是否存在静态配置表头tabPanelHeader
            if (this.tabPanelHeader && this.tabPanelHeader.length > 0) {
              // 按照这个tabPanelHeader顺序摆放
              for (let j = 0; j < this.tabPanelHeader.length; j++) {
                if (this.tabPanelHeader[j].tabType == tabNode.tabType) {
                  // 按照tabPanelHeader顺序摆放
                  this.pushDynamicTabs(j, tabNode);
                }
              }
            } else {
              // 判断是否有相同的
              let isAdd = true;
              for (let i = 0; i < this.dynamicTabs.length; i++) {
                if (this.dynamicTabs[i].tabType == tabNode.tabType) {
                  this.dynamicTabs.splice(i, 1, tabNode);
                  isAdd = false
                  break;
                }
              }
              if (isAdd) {
                // 按照顺序排放
                this.dynamicTabs.push(tabNode);
              }
            }
            break;
          }
        }
      } else {
        console.log("当前未配置展示方式。。。。");
      }

    },

    pushDynamicTabs(index, tabNode) {
      if (!this.dynamicTabs) {
        this.dynamicTabs = []
      }
      // 需要填充值
      for (let i = 0; i < this.tabPanelHeader.length; i++) {
        if (index == i) {
          this.dynamicTabs.splice(i, 1, tabNode);
          break;
        } else {
          let dynamicTab = this.dynamicTabs[i];
          // 如果有值
          if (dynamicTab) {
            // 不做处理
          }
          // 如果没有值
          else {
            // 需要填充值
            this.dynamicTabs.push({})
          }
        }
      }
    },


    /**
     * 初始化tab内容
     * @param {} tabNode
     * @param {*} that
     */
    initNav(tabNode, that) {
      this.executeEvent('initNav', that.path, tabNode, that)
    },
    beforeLeave(activeName, oldActiveName) {
      if (this.enabledHide) {
        // console.log("33333");
        this.cacheTab[oldActiveName] = null;
      }
    },
    /**
     * tab标签点击事件
     * @param {*} tabNode
     */
    tabClick(tabNode) {
      console.log(tabNode);
      if (this.enabledHide) {
        if (!this.cacheTab[tabNode.name]) {
          this.cacheTab[tabNode.name] = 1;
        } else {
          this.cacheTab[tabNode.name] = null;
          this.dynamicTabsValue = "-1";
        }
      }
      this.executeEvent('tabClick', this.path, tabNode)
    },
    removeTab(targetName) {
      let tabs = this.dynamicTabs;
      let activeName = this.dynamicTabsValue;
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.dynamicTabsValue = activeName;
      this.dynamicTabs = tabs.filter(tab => tab.name !== targetName);
    }
  },

  computed: {
    tabStyle() {
      return this.tabStyles;
    },
  }
}
</script>

<style lang="less" scoped>

</style>
